<template>
  <UploadExcel :before-upload="beforeUpload" :on-success="handleSuccess" />
</template>

<script>
import { batchAddEmployeeApi } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      type: this.$route.query.type
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      if (this.type === 'employees') {
        this.batchAddEmployee(results)
      }
    },
    /**
     * 添加excel的方法
     */
    async batchAddEmployee(results) {
      // console.log(results)
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }

      const list = []// 要接收的数组

      results.forEach(item => {
        const newObj = {} // 要push的新对象
        for (const key in item) {
          let value = item[key] // 新对象的value
          const newKey = userRelations[key]// 新对象的key
          if (['timeOfEntry', 'correctionTime'].includes(newKey)) {
            value = this.formatExcelDate(item[key])
          }
          newObj[newKey] = value // 新对象
          console.log(newObj)
        }
        list.push(newObj)
      })

      await batchAddEmployeeApi(list)
      this.$message.success(`上传成功`)
      this.$router.back()
    },
    /**
     * excel时间戳的转换方法
     *  */
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>>

